#define	_CRT_SECURE_NO_WARNINGS 1 

#include "SList.h"

void SLPrint(SLNode* phead)
{
	SLNode* cur = phead;
	while (cur != NULL)
	{
		printf("%d->", cur->val);
		cur = cur->next;
	}
	printf("NULL\n");
}
SLNode* CreatNode(SLNDataType x)
{
	SLNode* newnode = (SLNode*)malloc(sizeof(SLNode));
	if (newnode == NULL)
	{
		perror("CreatNode->malloc");
		exit(-1);
	}
	newnode->val = x;
	newnode->next = NULL;
	return newnode;
}
void SLPushFront(SLNode** pphead, SLNDataType x)
{
	SLNode* newnode = CreatNode(x);
	newnode->next = *pphead;
	*pphead = newnode;
}
void SLPushBack(SLNode** pphead, SLNDataType x)
{
	SLNode* newnode = CreatNode(x);
	if (*pphead == NULL)
	{
		*pphead = newnode;
	}
	else
	{
		SLNode* tail = *pphead;
		while (tail->next != NULL)
		{
			tail = tail->next;
		}
		tail->next = newnode;
	}
}
void SLPopFront(SLNode** pphead)
{
	assert(*pphead);
	SLNode* tmp = *pphead;
	*pphead = (*pphead)->next;
	free(tmp);
}
void SLPopBack(SLNode** pphead)
{
	assert(*pphead);
	if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	SLNode* tail = *pphead;
	while (tail->next->next != NULL)
	{
		tail = tail->next;
	}
	free(tail->next);
	tail->next = NULL;

}
SLNode* SLFind(SLNode** pphead, SLNDataType x)
{
	SLNode* tail = *pphead;
	while (tail != NULL)
	{
		if (tail->val == x)
		{
			return tail;
		}
		tail = tail->next;
	}
	return NULL;
}
void SLTInsert(SLNode** pphead, SLNode* pos, SLNDataType x)
{
	assert(pphead);
	assert(pos);
	assert(*pphead);
	SLNode* newnode = CreatNode(x);
	SLNode* cur = *pphead;
	while ( cur->next != pos)
	{
		cur = cur->next;
	}
	newnode->next = pos;
	cur->next = newnode;
}
void SLTErase(SLNode** pphead, SLNode* pos)
{
	assert(pphead);
	assert(*pphead);
	assert(pos);
	SLNode* cur = *pphead;
	while (cur->next != pos)
	{
		cur = cur->next;
	}
	cur->next = pos->next;
	free(pos);
}
void SLTDestroy(SLNode** pphead)
{
	SLNode* cur = *pphead;
	SLNode* des = NULL;
	while (cur != NULL)
	{
		des = cur;
		cur = cur->next;
		free(des);
	}
	*pphead = NULL;
}